/*
 * Copyright 2008 Marcos Silva Pereira
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.grails.plugins.envers;

import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;

/**
 * @author marcos.silva@gmail.com
 */
public class EnversAnnotationConfiguration extends GrailsAnnotationConfiguration {

	public static String ENVERS_CONFIGURATION_BEAN_NAME = "enversAnnotationConfiguration";

	@Override
	public void setGrailsApplication(GrailsApplication application) {

		super.setGrailsApplication(application);

		BeanDefinition configurationHolder = getBeanDefinition();

		BeanDefinitionRegistry registry = getBeanRegistry(application);
		registry.registerBeanDefinition(ENVERS_CONFIGURATION_BEAN_NAME, configurationHolder);

	}

	private BeanDefinitionRegistry getBeanRegistry(GrailsApplication application) {

		ApplicationContext mainContext = application.getParentContext();

		return 	(mainContext instanceof BeanDefinitionRegistry)
				? ((BeanDefinitionRegistry) mainContext)
				: (BeanDefinitionRegistry) ((XmlWebApplicationContext) mainContext).getBeanFactory();
		
	}

	private BeanDefinition getBeanDefinition() {

		MutablePropertyValues properties = new MutablePropertyValues();
		properties.addPropertyValue("configuration", this);

		BeanDefinition configurationHolder = new RootBeanDefinition(EnversAnnotationConfigurationHolder.class, properties);
		configurationHolder.setScope(BeanDefinition.SCOPE_SINGLETON);
		configurationHolder.setAutowireCandidate(false);

		return configurationHolder;

	}
}
